<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/7/12
 * Time: 14:18
 */

namespace app\admin\helper;


use ReflectionClass;
use think\Config;

class AclHelper
{

    /**
     * 获取当前控制器目录下所有的文件名
     * @return array
     */
    static private function redController(){
        $arr=scandir(__DIR__.DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'controller');
        unset($arr[0],$arr[1]);//因为这样获取到的数组前两位是. 和..,所以删去
        $list=[];
        foreach($arr as $k=>$v){
            $list[]=pathinfo($v,PATHINFO_FILENAME);
        }
        return $list;
    }

    /**
     * 获取当前控制器目录下所有的自定义方法
     * @param $class
     * @return array
     */
    static private function redFunction($class){
        $funs = [];
        $rClass = new ReflectionClass("\app\admin\controller\\".$class);
        $no_auth_list = Config::get('app.no_auth_list');
        if (isset($no_auth_list[$class])) {
            $no_auth_list = $no_auth_list[$class];
        }
        foreach ($rClass->getMethods() as $rMethod)
        {
            //过滤父类系统方法
            if (in_array($rMethod->name,['__construct','_initialize','beforeAction','fetch','display','assign',
                'engine','validateFailException','validate','success','error','result','redirect','getResponseType']))
                continue;
            //app config no_auth_list 不入权限
            if (!empty($no_auth_list) && in_array($rMethod->name,$no_auth_list))
                continue;
            $funs [] = $rMethod->name;
        }
        return $funs;
    }

    /**
     * 构建CA List
     * @return array
     */
    static public function buildCA(){
        $re = [];
        $list = self::redController();
        foreach ($list as $controllerName) {
            //过滤父类controller
            if ($controllerName == 'Base')
                continue;
            $funs = self::redFunction($controllerName);
            $re[$controllerName] = $funs;
        }
        return $re;
    }

    /**
     * 构建Butoon List
     * @return array
     */
    static public function buildButton(){
        $re = [];
        $menu = LangHelper::convertLang(Config::get('menu'));
        foreach ($menu as $link) {
            foreach ($link['sub_link'] as $link_name => $sub_item) {
                $buttons =  explode(',',$sub_item['button']);
                foreach ($buttons as $button) {
                    $re[$link['name']][$link_name][] = $sub_item['url'].'--'.$button;
                }
            }
        }
        return $re;
    }


}